package com.ningxun.pagentcrawler.service.policy.impl;

import com.ningxun.pagent.bus.domain.BusPolicyContent;
import com.ningxun.pagent.bus.mapper.BusPolicyContentMapper;
import com.ningxun.pagent.bus.service.IBusPolicyContentService;
import com.ningxun.pagent.common.core.domain.model.LoginUser;
import com.ningxun.pagent.common.utils.DateUtils;
import com.ningxun.pagent.common.utils.SecurityUtils;
import com.ningxun.pagent.flow.mapper.WarmFlowMapper;
import org.dromara.warm.flow.core.FlowEngine;
import org.dromara.warm.flow.core.dto.FlowParams;
import org.dromara.warm.flow.core.entity.Instance;
import org.dromara.warm.flow.core.entity.Task;
import org.dromara.warm.flow.core.service.InsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import static com.ningxun.pagent.flow.constant.FlowConstant.FLOW_NAME;

/**
 * 简化版政策内容服务实现类
 * 专门为爬虫模块提供，只包含爬虫需要的功能
 *
 * @author pagent
 * @date 2025-01-XX
 */
@Service
@Primary
public class SimpleBusPolicyContentServiceImpl implements IBusPolicyContentService {

    @Autowired
    private BusPolicyContentMapper busPolicyContentMapper;

    @Resource
    private WarmFlowMapper warmFlowMapper;

    @Resource
    private InsService insService;

    /**
     * 查询政策内容列表（爬虫用于去重检查）
     *
     * @param busPolicyContent 政策内容
     * @return 政策内容列表
     */
    @Override
    public List<BusPolicyContent> selectBusPolicyContentList(BusPolicyContent busPolicyContent) {
        return busPolicyContentMapper.selectBusPolicyContentList(busPolicyContent);
    }

    /**
     * 新增政策内容（爬虫用于保存数据）
     *
     * @param busPolicyContent 政策内容
     * @return 结果
     */
    @Override
    public int insertBusPolicyContent(BusPolicyContent busPolicyContent) {
        // 设置创建时间
        busPolicyContent.setCreateTime(new Date());

        // 直接插入数据库，不涉及工作流
        //加入工作流
        // 1. 先插入数据库
        int result = busPolicyContentMapper.insertBusPolicyContent(busPolicyContent);

        if (result > 0) {
            // 2. 插入成功后立即启动工作流
            try {
                startWorkflowForCrawler(busPolicyContent);
            } catch (Exception e) {
                // 如果工作流启动失败，可以记录日志但不影响数据插入
                    System.err.println("工作流启动失败，政策ID: " + busPolicyContent.getPolicyId() + ", 错误信息: " + e.getMessage());
            }
        }

        return result;
    }
    private void startWorkflowForCrawler(BusPolicyContent busPolicyContent) {
        // 获取当前时间
        Date nowDate = DateUtils.getNowDate();
        // 设置流转参数
        LoginUser user = null;
        try {
            user = SecurityUtils.getLoginUser();
        } catch (Exception e) {
            // 爬虫环境下获取用户信息失败，使用默认系统用户
            System.out.println("爬虫环境获取用户信息失败，使用默认系统用户");
        }

        // 如果获取不到用户信息，创建一个默认的系统用户
        if (user == null) {
            user = new LoginUser();
            // 创建一个默认用户对象，设置必要的用户信息
            com.ningxun.pagent.common.core.domain.entity.SysUser sysUser = new com.ningxun.pagent.common.core.domain.entity.SysUser();
            sysUser.setUserId(0L); // 使用系统默认用户ID
            sysUser.setUserName("crawler"); // 爬虫用户名
            sysUser.setNickName("爬虫系统");
            user.setUser(sysUser);
        }

        // 从字典表中获取流程编码
        busPolicyContent.setType(FLOW_NAME);
        String flowCode = warmFlowMapper.getFlowCodeByFlowName(busPolicyContent.getType());

        // 传递流程编码，绑定流程定义 【必传】
        FlowParams flowParams = FlowParams.build().flowCode(flowCode);
        // 设置办理人唯一标识，保存为流程实例的创建人 【必传】
        flowParams.handler(user.getUser().getUserId().toString());
        Long id = busPolicyContent.getPolicyId();
        Instance instance = insService.start(String.valueOf(id), flowParams);

        // 重要：设置实例ID到政策内容对象
        busPolicyContent.setInstanceId(instance.getId());

        // 获取第一个任务节点，用于设置初始状态
        List<Task> tasks = FlowEngine.taskService().getByInsId(instance.getId());
        if (!tasks.isEmpty()) {
            Task firstTask = tasks.get(0);
            busPolicyContent.setNodeCode(firstTask.getNodeCode());
            busPolicyContent.setNodeName(firstTask.getNodeName());
            busPolicyContent.setNodeType(Long.valueOf(firstTask.getNodeType()));
            busPolicyContent.setFlowStatus(instance.getFlowStatus());
        } else {
            // 如果没有任务，默认设置为流程实例状态
            busPolicyContent.setNodeCode(instance.getNodeCode());
            busPolicyContent.setNodeName(instance.getNodeName());
            busPolicyContent.setNodeType(Long.valueOf(instance.getNodeType()));
            busPolicyContent.setFlowStatus(instance.getFlowStatus());
        }

        // 再次更新政策内容表，包含实例ID和流程状态
        busPolicyContentMapper.updateBusPolicyContent(busPolicyContent);
    }

    // ========== 以下方法爬虫不需要，但为了兼容接口必须实现 ==========

    @Override
    public BusPolicyContent selectBusPolicyContentByPolicyId(Long policyId) {
        // 爬虫不需要，返回null
        return null;
    }

    @Override
    public int updateBusPolicyContent(BusPolicyContent busPolicyContent) {
        // 爬虫不需要，返回0
        return 0;
    }

    @Override
    public int updateBusPolicyContentWithWorkflow(BusPolicyContent busPolicyContent) {
        return 0;
    }

    @Override
    public int deleteBusPolicyContentByPolicyIds(Long[] policyIds) {
        // 爬虫不需要，返回0
        return 0;
    }

    @Override
    public int deleteBusPolicyContentByPolicyId(Long policyId) {
        // 爬虫不需要，返回0
        return 0;
    }

    @Override
    public void checkExpire() {
        // 爬虫不需要，空实现
    }

    @Override
    public List<BusPolicyContent> selectBusPolicyContentByPolicyIdList(List<Long> policyIds) {
        return null;
    }

    @Override
    public int submit(Long policyId, Long approveStatus) {
        // 爬虫不需要，返回0
        return 0;
    }

    @Override
    public int handle(BusPolicyContent busPolicyContent, String skipType, Long taskId, String message, String nodeCode, String flowStatus) {
        // 爬虫不需要，返回0
        return 0;
    }

    @Override
    public int rejectLast(BusPolicyContent busPolicyContent, Long taskId, String message, String flowStatus) {
        // 爬虫不需要，返回0
        return 0;
    }

    @Override
    public BusPolicyContent selectFrontBusPolicyContentByPolicyId(Long policyId) {
        return null;
    }

    @Override
    public List<BusPolicyContent> selectLatestPolicies(int limit) {
        return null;
    }
}
